package com.googlecode.restitory.api.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.googlecode.mycontainer.commons.regex.RegexUtil;
import com.googlecode.restitory.api.JsonHelper;

public class ServletHelper {

	private static final String PATTERN_CONTENT_TYPE = "([\\+\\w\\/-]*);{0,1}\\s*(charset=)*(([\\w-]*))";

	public static String getMediaType(String contentType) {
		if (contentType == null) {
			return null;
		}
		List<String> groups = RegexUtil.groups(PATTERN_CONTENT_TYPE,
				contentType);
		if (groups.isEmpty()) {
			return contentType;
		}
		String r = groups.get(1);
		if (r == null || r.length() == 0) {
			return contentType;
		}
		return r;
	}

	public static void write(HttpServletResponse resp, Object obj) {
		try {
			if (!(obj instanceof JsonElement)) {
				obj = JsonHelper.createBasic(obj);
			}
			if (obj instanceof JsonObject) {
				JsonObject json = (JsonObject) obj;
				Long lastModified = (Long) JsonHelper.jsonToBasicObject(json
						.get("_lastModified"));
				if (lastModified != null) {
					resp.setDateHeader("Last-Modified", lastModified);
				}
			}
			resp.setContentType("application/json");
			resp.setCharacterEncoding("UTF-8");
			resp.getWriter().write(obj.toString());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
